package openase.audio.record;

import java.util.concurrent.TimeUnit;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

import openase.audio.AudioFormat;
import openase.audio.AudioUtils;


public class MicrophoneAudioRecorder implements AudioRecorder {

    @Override
    public byte[] record(AudioFormat format, long time, TimeUnit unit) throws AudioRecordingException {
        DefaultAudioRecorder recorder = new DefaultAudioRecorder(getMicrophoneTargetDataLine(format));
        
        return recorder.record(format, time, unit);
    }

    private TargetDataLine getMicrophoneTargetDataLine(AudioFormat format) throws AudioRecordingException {
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, AudioUtils.asJavaSoundAudioFormat(format));
        try {
            TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
            if (line == null) {
                throw new AudioRecordingException("Microphone not found for format " + format);
            }
            return line;
        } catch (LineUnavailableException e) {
            throw new AudioRecordingException("Microphone not found for format " + format, e);
        }
    }

}
